/**
 * 任务服务
 */
const { validationResult } = require("express-validator");
const { poolPromise } = require("../db/index.js");

/**
 * 查询任务
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
async function selectTask(req, res, next) {
  const validationError = validationResult(req);
  if (!validationError.isEmpty()) {
    return res.status(400).json({
      code: 400,
      msg: validationError.errors[0].msg,
      errors: validationError.array(),
      data: null,
    });
  } else {
    try {
      let { currentPage = 1, pageSize = 2, status = 0 } = req.query;
      currentPage = parseInt(currentPage);
      pageSize = parseInt(pageSize);
      status = parseInt(status);
      const querySql = `select t.id,t.title,t.content,t.status,t.is_major,t.start_time,t.expire_time from task t`;
      const [taskList] = await poolPromise.query(querySql + " where status=?", [status]);
      const total = taskList.length; // 总条数
      if (!total) {
        return res.status(200).json({
          code: 200,
          msg: "暂无数据",
          total,
          currentPage,
          pageSize,
          data: [],
        });
      }
      const startIndex = (currentPage - 1) * pageSize; // 分页起始索引
      const queryStatusOrLimit = querySql + ` where status=? order by start_time desc limit ?,?`;
      const [result] = await poolPromise.query(queryStatusOrLimit, [status, startIndex, pageSize]);
      // console.log(result);
      res.status(200).json({
        code: 200,
        msg: "查询成功",
        total,
        currentPage,
        pageSize,
        data: result,
      });
    } catch (error) {
      next(error);
    }
  }
}

/**
 * 添加任务
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
async function insertTask(req, res, next) {
  const validationError = validationResult(req);
  if (!validationError.isEmpty()) {
    return res.status(400).json({
      code: 400,
      msg: validationError.errors[0].msg,
      errors: validationError.array(),
      data: null,
    });
  } else {
    const { title, content, status = 0, is_major = 0, start_time, expire_time } = req.body;
    const querySql = `select count(title) count from task where title=?`;
    const [[{ count }]] = await poolPromise.query(querySql, [title]);
    if (!!count) {
      return res.status(400).json({
        code: 400,
        msg: "任务名称已存在",
        data: null,
      });
    }

    const connection = await poolPromise.getConnection(); // 获取一个连接
    try {
      await connection.beginTransaction(); // 开启事务
      const insertSql = `insert into task(title,content,status,is_major,start_time,expire_time) values(?,?,?,?,?,?)`;
      const [{ affectedRows }] = await connection.execute(insertSql, [
        title,
        content,
        status,
        is_major,
        start_time,
        expire_time,
      ]);
      if (!affectedRows) {
        await connection.rollback(); // 回滚事务
        return res.status(400).json({
          code: 400,
          msg: "添加失败",
          data: null,
        });
      }
      await connection.commit(); // 提交事务
      res.status(200).json({
        code: 200,
        msg: "添加成功",
        data: null,
      });
    } catch (error) {
      await connection.rollback(); // 回滚事务
      next(error);
    } finally {
      connection.release(); // 释放连接
    }
  }
}

/**
 * 删除任务
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
async function deleteTask(req, res, next) {
  const validationError = validationResult(req);
  if (!validationError.isEmpty()) {
    return res.status(400).json({
      code: 400,
      msg: validationError.errors[0].msg,
      errors: validationError.array(),
      data: null,
    });
  }
  const { ids } = req.body;
  if (!ids || !ids.length) {
    return res.status(400).json({
      code: 400,
      msg: "ids参数不能为空",
      data: null,
    });
  }
  const connection = await poolPromise.getConnection();
  try {
    await connection.beginTransaction();
    // let placeholders = ids.map((item) => "?").join(",");
    const deleteSql = `delete from task where id in (${ids.join(",")})`;
    const [{ affectedRows }] = await connection.execute(deleteSql);
    if (!affectedRows) {
      await connection.rollback();
      return res.status(400).json({
        code: 400,
        msg: "删除失败",
        data: null,
      });
    }

    await connection.commit();
    res.status(200).json({
      code: 200,
      msg: "删除成功",
      data: null,
    });
  } catch (error) {
    await connection.rollback();
    next(error);
  } finally {
    connection.release();
  }
}

/**
 * 修改任务
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
async function updateTask(req, res, next) {
  const validationError = validationResult(req);
  if (!validationError.isEmpty()) {
    return res.status(400).json({
      code: 400,
      msg: validationError.errors[0].msg,
      errors: validationError.array(),
      data: null,
    });
  } else {
    const { id, title, content, status, is_major, start_time, expire_time } = req.body;
    const querySql = `select count(title) count from task where title=?`;
    const [[{ count }]] = await poolPromise.query(querySql, [title]);
    if (!!count) {
      return res.status(400).json({
        code: 400,
        msg: "任务名称已存在",
        data: null,
      });
    }

    const connection = await poolPromise.getConnection();
    try {
      await connection.beginTransaction();
      const updateSql = `update task set title=?,content=?,status=?,is_major=?,start_time=?,expire_time=? where id=?`;
      const [{ affectedRows }] = await connection.execute(updateSql, [
        title,
        content,
        status,
        is_major,
        start_time,
        expire_time,
        id,
      ]);
      if (!affectedRows) {
        await connection.rollback();
        return res.status(400).json({
          code: 400,
          msg: "修改失败",
          data: null,
        });
      }

      await connection.commit();
      res.status(200).json({
        code: 200,
        msg: "修改成功",
        data: null,
      });
    } catch (error) {
      await connection.rollback();
      next(error);
    } finally {
      connection.release();
    }
  }
}

/**
 * 修改任务状态
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
async function updateTaskStatus(req, res, next) {
  const validationError = validationResult(req);
  if (!validationError.isEmpty()) {
    return res.status(400).json({
      code: 400,
      msg: validationError.errors[0].msg,
      errors: validationError.array(),
      data: null,
    });
  } else {
    const { id, status } = req.body;
    const connection = await poolPromise.getConnection();
    try {
      await connection.beginTransaction();
      const updateSql = `update task set status=? where id=?`;
      const [{ affectedRows }] = await connection.execute(updateSql, [status, id]);
      if (!affectedRows) {
        await connection.rollback();
        return res.status(400).json({
          code: 400,
          msg: "修改失败",
          data: null,
        });
      }

      connection.commit();
      res.status(200).json({
        code: 200,
        msg: "修改成功",
        data: null,
      });
    } catch (error) {
      await connection.rollback();
      next(error);
    } finally {
      connection.release();
    }
  }
}

/**
 * 修改任务是否为重要
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
async function updateTaskMajor(req, res, next) {
  const validationError = validationResult(req);
  if (!validationError.isEmpty()) {
    return res.status(400).json({
      code: 400,
      msg: validationError.errors[0].msg,
      errors: validationError.array(),
      data: null,
    });
  } else {
    const { id, is_major } = req.body;

    const connection = await poolPromise.getConnection();

    try {
      await connection.beginTransaction();
      const updateSql = `update task set is_major=? where id=?`;
      const [{ affectedRows }] = await connection.execute(updateSql, [is_major, id]);
      if (!affectedRows) {
        await connection.rollback();
        return res.status(400).json({
          code: 400,
          msg: "修改失败",
          data: null,
        });
      }

      connection.commit();
      res.status(200).json({
        code: 200,
        msg: "修改成功",
        data: null,
      });
    } catch (error) {
      connection.rollback();
      next(error);
    } finally {
      connection.release();
    }
  }
}

module.exports = {
  selectTask,
  insertTask,
  deleteTask,
  updateTask,
  updateTaskStatus,
  updateTaskMajor,
};
